package top.jacktgq.sxt.bio.error_discrimination;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 * @author CandyWall
 *
 */
public class TcpServer {
	private static Boolean isRunning = true;
	//将多个4G模块采集到的数据保存到
	private static ConcurrentHashMap<String, FIFOImpl<Wavelet_sample_data>> wavelet_sample_data_queueMap = new ConcurrentHashMap<String, FIFOImpl<Wavelet_sample_data>>();
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(8888);
		System.out.println("服务器已启动...");
		while(isRunning) {
			Socket socket = serverSocket.accept();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			System.out.println(sdf.format(new Date()) + "：一个客户端连接成功！");
			new Thread(new Runnable() {

				@Override
				public void run() {
					String ws_id = null;
					try {
						BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
						ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
						String line = null;

						String acqu_id = null;
						if((line = br.readLine()) != null) {
							//如果发来的第一行数据中不包含#号，代表发数据的是客户端，否则即为4G采集端
							if (!line.contains("#")) {
								System.out.println(line);
								/*for (Wavelet_sample_data wavelet_sample_data : wavelet_sample_data_queueMap.get(line)) {
									System.out.println(wavelet_sample_data);
								}*/
								FIFOImpl<Wavelet_sample_data> wavelet_sample_data_queue = wavelet_sample_data_queueMap.get(line);
								Wavelet_sample_data[] wavelet_sample_datas = new Wavelet_sample_data[wavelet_sample_data_queue.size()];
								wavelet_sample_data_queue.toArray(wavelet_sample_datas);
								oos.writeObject(wavelet_sample_datas);
								//oos.writeObject(new Integer(5));
							} else {
								String[] str = line.split("#");
								//分析第一条从4G模块处发送过来的数据，提取出数据采集设备编号
								acqu_id = str[1];
								//根据4G模块编号查询这个4G模块和哪个小波分析样本绑定在一起，在数据库中查询样本编号、时长、步长
								Connection conn = DBUtils.getConn();
								try {
									PreparedStatement pstm = conn.prepareStatement("SELECT ws_id, duration, step_size FROM wavelet_sample WHERE ws_id = '0000a0000b0000c0000d0000e0000f0000g10'");
									ResultSet rs = pstm.executeQuery();
									if (rs.next()) {
										ws_id = rs.getString("ws_id");
										double duration = rs.getDouble("duration");
										double step_size = rs.getDouble("step_size");
										System.out.println("ws_id:" + ws_id + ",duration:" + duration + ",step_size:" + step_size);
										//为每个4G模块创建一个固定长度（数据采集样本中的时长和步长的商）的队列，将采集到的数据都存储到这个队列中，
										FIFOImpl<Wavelet_sample_data> wavelet_sample_data_queue = new FIFOImpl<Wavelet_sample_data>();
										wavelet_sample_data_queue.setMaxSize((int) (duration / step_size));
										wavelet_sample_data_queueMap.put(ws_id, wavelet_sample_data_queue);
									}
									conn.close();
								} catch (SQLException e) {
									e.printStackTrace();
								}
								while((line = br.readLine()) != null) {
									str = line.split("#");
									Wavelet_sample_data wavelet_sample_data = new Wavelet_sample_data();
									wavelet_sample_data.setAcqu_checkId(str[0]);
									wavelet_sample_data.setAcqu_id(str[1]);
									wavelet_sample_data.setVoltage(Double.parseDouble(str[2]));
									wavelet_sample_data.setAcqu_time(new Date());
									//根据4G模块编号获取对应的数据存储队列
									wavelet_sample_data_queueMap.get(ws_id).addLastSafe(wavelet_sample_data);
								}
								for (Wavelet_sample_data wavelet_sample_data : wavelet_sample_data_queueMap.get(ws_id)) {
									System.out.println(wavelet_sample_data);
								}

							}


						}

					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}
}
